package com.wfc.servlet.cook;

import com.wfc.entity.Cook;
import com.wfc.entity.Dish;
import com.wfc.service.CookService;
import com.wfc.service.DishService;
import com.wfc.service.serviceImpl.CookServiceImpl;
import com.wfc.service.serviceImpl.DishServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

@WebServlet("/uploadCook")
public class uploadCook extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        int id =0;
        int cid =0;
        String uname=null;
        String dname =null;
        String detail = null;//菜品介绍
        String mainfood =null;
        String fufood =null;
        String tiaofood =null;
        String process ="";
        String cooking =null;
        String pic = null;//存菜品最终图
        String pic1=null;
        String pic2 = null;
        String pic3 =null;
        String cooktext =null;
        int love =0;
        String  state= null;


        String level =null;//难度
        String during =null;//时间


        String cuisine =null;//口味
        String technics =null;//工艺
        String cookers =null;//厨具

        String category= null;



        //picPath
        //上传图片
        boolean isMultipartFile = ServletFileUpload.isMultipartContent(req);
        String path = "D:\\project\\FCM\\web\\image";
        String pa = "http://localhost:8080/image/";
        File o_file = new File(path);

//        String picPath = null;
        if(!o_file.exists()){
            o_file.mkdir();
        }

        if(isMultipartFile) {
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//      String charset  =  request.getCharacterEncoding();
//      if  (charset  !=   null ) {
//        servletFileUpload.setHeaderEncoding(charset);
//      }
            List<FileItem> list = null;
            try {
                list = servletFileUpload.parseRequest(req);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator<FileItem> iterator = list.iterator();
            while (iterator.hasNext()) {

                FileItem item = iterator.next();
                boolean formField = item.isFormField();
                if (!formField) {
                    String fieldName1 = item.getFieldName();
                    if(fieldName1.equals("file")){
                        String fileUpdate = item.getName();
                        File m_file = new File(fileUpdate);
                        if (m_file.getName() != null && !(m_file.getName().equals(""))) {
                            File file = new File(path + "\\" + m_file.getName());
                            try {
                                item.write(file);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(file.getPath());
                            pic = pa + file.getName();
                            System.out.println(cooking);
                    }

                    }else if(fieldName1.equals("file1")){
                        String fileUpdate = item.getName();
                        File m_file = new File(fileUpdate);
                        if (m_file.getName() != null && !(m_file.getName().equals(""))) {
                            File file = new File(path + "\\" + m_file.getName());
                            try {
                                item.write(file);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(file.getPath());
                            pic1 = pa + file.getName();
                            System.out.println(cooking);
                        }
                    }else if(fieldName1.equals("file2")){
                        String fileUpdate = item.getName();
                        File m_file = new File(fileUpdate);
                        if (m_file.getName() != null && !(m_file.getName().equals(""))) {
                            File file = new File(path + "\\" + m_file.getName());
                            try {
                                item.write(file);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(file.getPath());
                            pic2 = pa + file.getName();
                            System.out.println(cooking);
                        }
                        }else if(fieldName1.equals("file3")){
                        String fileUpdate = item.getName();
                        File m_file = new File(fileUpdate);
                        if (m_file.getName() != null && !(m_file.getName().equals(""))) {
                            File file = new File(path + "\\" + m_file.getName());
                            try {
                                item.write(file);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            System.out.println(file.getPath());
                            pic3 = pa + file.getName();
                            System.out.println(cooking);
                        }
                    }
                } else {
                    String fieldName = item.getFieldName();
                    if (fieldName.equals("uname")) {
                        uname = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                        System.out.println(uname);
                    }
                    else if (fieldName.equals("id")) {
                        if(!"null".equals(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")) && !"".equals(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8"))){
                            id = Integer.parseInt(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim());
                        }
                        System.out.println(id);
                    }else if (fieldName.equals("cid")) {
                        if(!"null".equals(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")) && !"".equals(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8"))){
                            cid = Integer.parseInt(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim());
                        }

                        System.out.println(cid);
                    }
                    else if (fieldName.equals("subject")) {
                        dname = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                        System.out.println(dname);
                    } else if (fieldName.equals("message")) {
                        detail = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                        System.out.println(detail);
                    } else if (fieldName.equals("level")) {
                        level = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                        System.out.println(level);

                        if("null".equals(item.getString().trim())){
                            if (Integer.parseInt(item.getString().trim()) == 1) {
                                level = "简单";
                            }
                            else if (Integer.parseInt(item.getString().trim()) == 2) {
                                level = "初级";
                            } else if (Integer.parseInt(item.getString().trim()) == 3) {
                                level = "中级";
                            } else if (Integer.parseInt(item.getString().trim()) == 4) {
                                level = "高级";
                            }
                        }

                    } else if (fieldName.equals("during")) {
                        if (Integer.parseInt(item.getString().trim()) == 1) {
                            during = "十分钟";
                        } else if (Integer.parseInt(item.getString().trim()) == 2) {
                            during = "半小时";
                        } else if (Integer.parseInt(item.getString().trim()) == 3) {
                            during = "一小时";
                        } else if (Integer.parseInt(item.getString().trim()) == 4) {
                            during = "一天";
                        }
                    } else if (fieldName.equals("cuisine")) {
                        cuisine = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("technics")) {
                        technics = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("cookers")) {
                        cookers = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("mainfood")) {
                        mainfood = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("myong")) {
                        assert mainfood != null;
                        mainfood = mainfood.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    } else if (fieldName.equals("fufood")) {
                        fufood = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("fyong")) {
                        assert fufood != null;
                        fufood = fufood.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    } else if (fieldName.equals("tiaofood")) {
                        tiaofood = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("tyong")) {
                        assert tiaofood != null;
                        tiaofood = tiaofood.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    } else if (fieldName.equals("note1")) {
                        cooktext = new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8").trim();
                    } else if (fieldName.equals("note2")) {
                        cooktext = cooktext.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    } else if (fieldName.equals("note3")) {
                        cooktext = cooktext.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    } else if (fieldName.equals("tips")) {
                        cooktext = cooktext.concat("&").concat(new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    }else if (fieldName.equals("state")) {
                        state = (new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    }else if (fieldName.equals("category")) {
                        category = (new String((item.getString("iso8859-1")).getBytes("iso8859-1"), "utf-8")).trim();
                    }
                }
            }
        }
                    Cook cook = new Cook();
                    Dish dish = new Dish();

        System.out.println("=========="+uname);
                    cook.setDname(dname);
                    cook.setUname(uname);
                    cook.setMainfood(mainfood);
                    cook.setFufood(fufood);
                    cook.setTiaofood(tiaofood);
                    if(process != null){
                        process=cuisine+"&"+technics+"&"+cookers+"&"+during+"&"+level;
                    }
                    cook.setProcess(process);
                    cook.setMainfood(mainfood);
                    cook.setFufood(fufood);
                    cook.setTiaofood(tiaofood);
                    cooking = pic1+"&"+pic2+"&"+pic3;
                    cook.setCooking(cooking);
                    cook.setCooktext(cooktext);

                    dish.setDname(dname);
                    dish.setUname(uname);
                    dish.setImg(pic);
                    dish.setDetail(detail);
                    dish.setLove(love);
                    dish.setCategory(category);

//
        CookService cookService = new CookServiceImpl();
        DishService dishService = new DishServiceImpl();
        if("修改".equals(state)){

            dish.setId(id);
            cook.setId(cid);
            int update1 = cookService.update(cook);
            dish.setId(dishService.selectBydname(dname).getId());
//            boolean b = dishService.addDish(dish);
            int update = dishService.update(dish);
            if(update1>0 && update>0) {
//                        req.getRequestDispatcher("/member.jsp?mes='发布菜谱成功！'").forward(req,resp);
                HttpSession session = req.getSession();
                session.removeAttribute("cookingimgs");
                session.removeAttribute("mainfoods");
                session.removeAttribute("fufoods");
                session.removeAttribute("tiaofoods");
                session.removeAttribute("processs");
                session.removeAttribute("cookTexts");
                session.removeAttribute("state");
                session.removeAttribute("xid");

                String res =  URLEncoder.encode(uname,"utf-8");

                resp.sendRedirect(req.getContextPath() + "/myDishServlet?username=" + res);
            }
        }else {
                boolean b1 = cookService.addCook(cook);
                boolean b = dishService.addDish(dish);
            if(b==true && b1 == true) {
//                        req.getRequestDispatcher("/member.jsp?mes='发布菜谱成功！'").forward(req,resp);
                String res =  URLEncoder.encode(uname,"utf-8");
                resp.sendRedirect(req.getContextPath() + "/myDishServlet?username=" + res);

            }
        }




    }
}
